<template>
  <div class="ai-model-config-list">
    <div class="config-header">
      <h3>AI模型配置列表</h3>
      <el-button type="primary" @click="handleAddConfig">
        <el-icon><Plus /></el-icon> 添加配置
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="configList"
      stripe
      border
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" min-width="120" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getModelTypeTag(row.type)">{{ getModelTypeName(row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="model" label="模型" min-width="120" />
      <el-table-column prop="baseUrl" label="API地址" min-width="180" show-overflow-tooltip />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.isEnabled"
            :disabled="row.isDefault"
            @change="(val: boolean) => handleStatusChange(row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="默认" width="80">
        <template #default="{ row }">
          <el-tag v-if="row.isDefault" type="success">默认</el-tag>
          <el-button
            v-else
            type="primary"
            link
            @click="handleSetDefault(row)"
          >
            设为默认
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="使用统计" width="120">
        <template #default="{ row }">
          <div>调用: {{ row.usageCount || 0 }}次</div>
          <div>Token: {{ formatTokens(row.totalTokens) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEditConfig(row)">
            编辑
          </el-button>
          <el-button type="primary" link @click="handleTestConnection(row)">
            测试连接
          </el-button>
          <el-popconfirm
            title="确定删除此配置吗？"
            @confirm="handleDeleteConfig(row)"
          >
            <template #reference>
              <el-button
                type="danger"
                link
                :disabled="row.isDefault"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 配置表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑AI模型配置' : '添加AI模型配置'"
      width="650px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入配置名称" />
        </el-form-item>

        <el-form-item label="模型类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择模型类型" style="width: 100%">
            <el-option
              v-for="item in modelTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="API密钥" prop="apiKey">
          <el-input
            v-model="formData.apiKey"
            placeholder="请输入API密钥"
            show-password
          />
        </el-form-item>

        <el-form-item label="API密钥2" prop="apiSecret">
          <el-input
            v-model="formData.apiSecret"
            placeholder="请输入API密钥2（可选）"
            show-password
          />
        </el-form-item>

        <el-form-item label="组织ID" prop="orgId">
          <el-input
            v-model="formData.orgId"
            placeholder="请输入组织ID（可选）"
          />
        </el-form-item>

        <el-form-item label="API地址" prop="baseUrl">
          <el-input
            v-model="formData.baseUrl"
            placeholder="请输入API地址"
          />
        </el-form-item>

        <el-form-item label="模型名称" prop="model">
          <el-input
            v-model="formData.model"
            placeholder="请输入模型名称"
          />
        </el-form-item>

        <el-form-item label="最大Token" prop="maxTokens">
          <el-input-number
            v-model="formData.maxTokens"
            :min="0"
            :max="100000"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="温度" prop="temperature">
          <el-slider
            v-model="formData.temperature"
            :min="0"
            :max="2"
            :step="0.1"
            show-input
          />
        </el-form-item>

        <el-form-item label="Top P" prop="topP">
          <el-slider
            v-model="formData.topP"
            :min="0"
            :max="1"
            :step="0.1"
            show-input
          />
        </el-form-item>

        <el-form-item label="超时时间" prop="timeout">
          <el-input-number
            v-model="formData.timeout"
            :min="0"
            :max="300000"
            :step="1000"
            style="width: 100%"
          >
            <template #suffix>毫秒</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="isEnabled">
          <el-switch v-model="formData.isEnabled" />
        </el-form-item>

        <el-form-item label="默认配置" prop="isDefault">
          <el-switch v-model="formData.isDefault" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTestFormData">测试连接</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useAIModelStore } from '../store/aiModel';
import { AIModelType } from '../api/aiModel';

// 初始化Store
const aiModelStore = useAIModelStore();

// 数据加载状态
const loading = computed(() => aiModelStore.loading);
const submitting = computed(() => aiModelStore.submitting);

// 配置列表
const configList = computed(() => aiModelStore.configList);

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();

// 对话框显示状态
const dialogVisible = ref(false);
const isEdit = ref(false);

// 模型类型选项
const modelTypeOptions = [
  { label: 'OpenAI', value: AIModelType.OPENAI },
  { label: 'Azure OpenAI', value: AIModelType.AZURE },
  { label: 'Anthropic', value: AIModelType.ANTHROPIC },
  { label: '百度文心一言', value: AIModelType.BAIDU },
  { label: '讯飞星火', value: AIModelType.XFYUN },
  { label: '智谱AI', value: AIModelType.ZHIPU },
  { label: '硅基流动', value: AIModelType.SILICON_FLOW },
  { label: '其他', value: AIModelType.OTHER },
];

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  type: AIModelType.OPENAI,
  apiKey: '',
  apiSecret: '',
  orgId: '',
  baseUrl: '',
  model: '',
  maxTokens: 2000,
  temperature: 0.7,
  topP: 0,
  timeout: 30000,
  isDefault: false,
  isEnabled: true,
  description: '',
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ],
  apiKey: [
    { required: true, message: '请输入API密钥', trigger: 'blur' }
  ],
  baseUrl: [
    { required: true, message: '请输入API地址', trigger: 'blur' }
  ]
};

// 获取模型类型名称
const getModelTypeName = (type: string) => {
  const option = modelTypeOptions.find(opt => opt.value === type);
  return option ? option.label : type;
};

// 获取模型类型标签样式
const getModelTypeTag = (type: string) => {
  switch (type) {
    case AIModelType.OPENAI:
      return '';
    case AIModelType.AZURE:
      return 'info';
    case AIModelType.ANTHROPIC:
      return 'warning';
    case AIModelType.BAIDU:
      return 'success';
    case AIModelType.XFYUN:
      return 'danger';
    case AIModelType.ZHIPU:
      return 'warning';
    case AIModelType.SILICON_FLOW:
      return 'success';
    default:
      return 'info';
  }
};

// 格式化Token数量
const formatTokens = (tokens: number | undefined) => {
  if (!tokens) return '0';
  if (tokens < 10000) return tokens.toString();
  return `${(tokens / 1000).toFixed(1)}K`;
};

// 添加配置
const handleAddConfig = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑配置
const handleEditConfig = (row: any) => {
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除配置
const handleDeleteConfig = async (row: any) => {
  try {
    await aiModelStore.deleteConfig(row.id);
  } catch (error) {
    console.error('删除配置失败:', error);
  }
};

// 设置默认配置
const handleSetDefault = async (row: any) => {
  try {
    await aiModelStore.setDefaultConfig(row.id);
  } catch (error) {
    console.error('设置默认配置失败:', error);
  }
};

// 修改配置状态
const handleStatusChange = async (row: any, isEnabled: boolean) => {
  try {
    await aiModelStore.changeConfigStatus(row.id, isEnabled);
  } catch (error) {
    // 恢复原状态
    row.isEnabled = !isEnabled;
    console.error('修改配置状态失败:', error);
  }
};

// 测试连接
const handleTestConnection = async (row: any) => {
  try {
    await aiModelStore.testConnection(row);
  } catch (error) {
    console.error('测试连接失败:', error);
  }
};

// 测试表单数据连接
const handleTestFormData = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        await aiModelStore.testConnection(formData);
      } catch (error) {
        console.error('测试连接失败:', error);
      }
    } else {
      console.log('表单验证失败', fields);
      ElMessage.error('请先完成必填项');
    }
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await aiModelStore.updateConfig(formData.id, formData);
        } else {
          await aiModelStore.createConfig(formData);
        }
        dialogVisible.value = false;
      } catch (error) {
        console.error('保存配置失败:', error);
      }
    } else {
      console.log('表单验证失败', fields);
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  // 重置为默认值
  Object.assign(formData, {
    id: '',
    name: '',
    type: AIModelType.OPENAI,
    apiKey: '',
    apiSecret: '',
    orgId: '',
    baseUrl: '',
    model: '',
    maxTokens: 2000,
    temperature: 0.7,
    topP: 0,
    timeout: 30000,
    isDefault: false,
    isEnabled: true,
    description: '',
  });
};

// 页面加载时获取配置列表
onMounted(async () => {
  try {
    await aiModelStore.fetchConfigList();
  } catch (error) {
    console.error('获取配置列表失败:', error);
  }
});
</script>

<style scoped>
.ai-model-config-list {
  padding: 20px;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.config-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 